# -*- coding:utf-8 -*-

import datetime
import time
import math
import coord
import tornado.ioloop

def handle_bus_message(msg):
    bus_data = parse_message(msg)
    handle_bus_data(bus_data)

buses = {}
buses_state = {}

def handle_bus_data(bus_data):      
    name = bus_data["Name"]
    if bus_data.name not in buses:
        bus = {"Name":name, "Stop":False, "Fly":False}
        buses[bus_data.name] = bus
        state = {}
        buses_state[name] = state
    else:
        bus = buses[name]
        state = buses_state[name]
    
    if "Time" in bus and bus["Time"]>=bus_data["Time"]:
        return
        
    bus["Stop"] = False
    bus["Fly"] = False
    bus["Longitude"] = bus_data["Longitude"]
    bus["Latitude"] = bus_data["Latitude"]
    
    station_index, percent, distance, coord_index = get_closest(bus["Latitude"], bus["Longitude"])
    
    if distance > 0.5:
        bus["Fly"] = True
        # log here
        return
    
    if index==0:
        bus["StationIndex"] = 1
        bus["Station"] = IndexToStation[1]
    else:
        bus["StationIndex"] = index
        bus["Station"] = IndexToStation[index]
        
    if "coord_index" in state:
        if state["coord_index"] > coord_index:
            bus["Direction"] = True
        elif: state["coord_index"] < coord_index:
            bus["Direction"] = False
    
    if index==1 and percent<0 or index==0:
        percent = 0
        
    if bus["Direction"] = True:
        percent *= -1
        
    bus["Pencent"] = percent
    if index==0:
        bus["Stop"] = True
    else:
        bus["Time"] = bus_data["Time"]
        
    state["coord_index"] = coord_index
    
    def _timeout():
        bus["Stop"] = True
    
    if "timeout" in state and state["timeout"] is not None:
        tornado.ioloop.IOLoop.instance().remove_timeout(state["timeout"])
        state["timeout"] = None        
    state["timeout"] = tornado.ioloop.IOLoop.instance().add_timeout(time.time()+5*60, _timeout)
    
def parse_message(msg):
    if msg is None or len(msg)==0:
        return
    fields = msg.split(',')
    if len(fields) < 11:
        return
    name = fields[0].strip()
    latitude = dm2d(float(fields[4]))
    longitude = dm2d(float(fields[6]))
    _date = fields[10]
    _time = fields[2]
    timestamp = time.mktime(time.strptime(' '.join((_date, _time)), "%d%m%y %H%M%S"))
    
    return {"Name": name, "Latitude": latitude, "Longitude": longitude, "Time", timestamp}

# 计算地球两经纬度间距离
def calc_distance(lat1, lgt1, lat2, lgt2):
    lat1, lgt1, lat2, lgt2 = d2r(lat1), d2r(lgt1), d2r(lat2), d2r(lgt2)
    dlat = lat2 - lat1
    dlgt = lgt2 - lgt1
    distance = 2 * math.asin(math.sqrt(math.Sin(dlat/2) ** 2 +
		math.cos(lat1)*math.cos(lat2)*(math.Sin(dlgt/2)**2))) * 6378.137

# 角分换算为角度
def dm2d(dm):
    return int(dm/100) + (dm%100)/60
    
# 角度换算为弧度
def d2r(d):
    return d / 360 * 2 * math.pi
    
# 获取离坐标最近的 coord
def get_closest(lat, lgt):
    shortest = float("inf")
    for i, coord in enumerate(data.Coords):
        distance = calc_distance(lat, lgt, coord.Latitude, coord.Longitude)
        if distance < shortest:
            shortest = distance
            station_index = coord_station_index(coord)
            percent = coord_percent(coord)
            coord_index = i
    return station_index, percent, distance, coord_index
